package com.spring.utils.api_v4.config;

import com.spring.utils.api_v4.interceptor.ResponseResultInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebAppConfig implements WebMvcConfigurer {
    // SpringMVC 需要手动添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        ResponseResultInterceptor interceptor = new ResponseResultInterceptor();
        registry.addInterceptor(interceptor);
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    /**
     * 设置跨域访问
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            // 当设置 setAllowCredentials(true)时，不能addAllowedOrigin("*") 需要具体的地址
            // .allowedOrigins("http://localhost:8080", "http://192.168.5.1", "http://172.20.4.25:8080")
            // .allowCredentials(true)
            .allowedHeaders("*")
            .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")
            .maxAge(3600 * 24)
            .allowedOrigins("*");
    }

//    @Override
//    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
//        FastJsonConfig fastJsonConfig = new FastJsonConfig();
//        fastJsonConfig.setSerializerFeatures(
//            // 结果是否格式化,默认为false
//            SerializerFeature.PrettyFormat,
//            // 是否输出值为null的字段,默认为false
//            SerializerFeature.WriteMapNullValue,
//            // 字符类型字段如果为null,输出为”“,而非null
//            SerializerFeature.WriteNullStringAsEmpty,
//            // Boolean字段如果为null,输出为false,而非null
//            SerializerFeature.WriteNullBooleanAsFalse,
//            // 数值字段如果为null,输出为0,而非null
//            SerializerFeature.WriteNullNumberAsZero,
//            // 消除对同一对象循环引用的问题，默认为false
//            // SerializerFeature.DisableCircularReferenceDetect,
//            // List字段如果为null,输出为[],而非null
//            SerializerFeature.WriteNullListAsEmpty);
//        converter.setFastJsonConfig(fastJsonConfig);
//        converters.add(0, converter);
//    }
}
